package com.etc;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
import java.util.UUID;

public class MyTimer extends TimerTask {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH");
    String date = dateFormat.format(new Date());

    @Override
    public void run() {
        moveFileToNewPath("D:/logs/accesslog", "D:/logs/toupload");
        moveFileToNewPath("D:/logs/toupload", "D:/logs/backup");
        try {
            init();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void moveFileToNewPath(String beffile, String endfile) {
        File file = new File(beffile);
        File[] files2 = file.listFiles(new MyFilter());
        File toupload = new File(endfile);
        if (!toupload.exists()) {
            toupload.mkdirs();
        }
        for (File a : files2) {
            a.renameTo(new File(toupload + "/" + a.getName() + date));
        }
    }

    private void init() throws URISyntaxException, IOException, InterruptedException {
        FileSystem fs = null;
        Configuration configuration = new Configuration();

        fs = FileSystem.get(new URI("hdfs://192.168.88.102:9000"), configuration, "root");
        File file = new File("D:/logs/toupload");
        File[] files = file.listFiles();
        File toupload = new File("D:/logs/backup");

        for (File file1 : files) {
            FileInputStream in = new FileInputStream(file1);
            OutputStream out = fs.create(new Path("/logs/" + UUID.randomUUID() + "accesslog_" + ".logs"));
            IOUtils.copyBytes(in, out, 4000, true);

            //把文件放入备份去/toupload.renameTo(new File(toupload + "/" + file1.getName() + date));
        }
        fs.close();
    }

}


